﻿using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Web.Configuration;

namespace QTMusic.BaseClasses
{
    /// <summary>
    /// Summary description for Common
    /// </summary>
    public static class Common
    {
        public enum Permission
        {
            Private,
            Friend,
            Public
        }

        public static readonly string connString =
            WebConfigurationManager.ConnectionStrings["QTConnection"].ConnectionString;

        public static string urlProfileImages = "~/ProfileImages/";
        public static string urlWebsites = "~/Websites/";

        public static string defaultImage = urlProfileImages + "defaultpic.jpg";

        public static string GetUserImgUrl(int userId)
        {
            string imgUrl = "";
            string selectSQL = "SELECT user_pic FROM [user] WHERE user_id = @userId";
            SqlConnection conn = new SqlConnection(Common.connString);
            SqlCommand cmd = new SqlCommand(selectSQL, conn);
            cmd.Parameters.AddWithValue("@userId", userId);
            SqlDataReader reader;

            try
            {
                using (conn)
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    reader.Read();
                    if (reader.HasRows)
                        imgUrl = (string)reader[0];
                }
            }
            catch (Exception commonE)
            {
                WriteToEventLog(commonE, "Common.GetUserImgUrl");
                imgUrl = defaultImage;
            }
            return imgUrl;
        }

        public static string GetUserName(int userId)
        {
            string userName = "";
            string selectSQL = "SELECT user_name FROM [user] " +
                               "WHERE user_id = @userId";
            SqlConnection conn = new SqlConnection(Common.connString);
            SqlCommand cmd = new SqlCommand(selectSQL, conn);
            cmd.Parameters.AddWithValue("@userId", userId);
            SqlDataReader reader;

            try
            {
                using (conn)
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    reader.Read();
                    if (reader.HasRows)
                        userName = (string)reader[0];
                }
            }
            catch (Exception commonE)
            {
                WriteToEventLog(commonE, "Common.GetUserName");
                userName = "";
            }
            return userName;
        }

        public static bool IsFriend(int userId, int userIdToCheck)
        {
            bool isFriend = false;
            string selectSQL = "SELECT friend_id FROM [friend] WHERE user_id = @userId";
            SqlConnection conn = new SqlConnection(Common.connString);
            SqlCommand cmd = new SqlCommand(selectSQL, conn);
            cmd.Parameters.AddWithValue("@userId", userId);
            SqlDataReader reader;

            try
            {
                using (conn)
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        if ((int)reader[0] == userIdToCheck)
                        {
                            isFriend = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception commonE)
            {
                WriteToEventLog(commonE, "Common.IsFriend");
                isFriend = false;
            }
            return isFriend;
        }

        // return 0: not sent yet
        // return 1: sent, waiting for response
        // return 2: sent, accepted or denied
        public static int IsRequestSent(int idFrom, int idTo)
        {
            string selectRequest = "SELECT * FROM [friendreq] "
                                            + "WHERE friendreq_from_id = @idFrom "
                                            + "AND user_id = @idTo";
            SqlConnection conn = new SqlConnection(Common.connString);
            SqlCommand cmd = new SqlCommand(selectRequest, conn);
            cmd.Parameters.AddWithValue("@idFrom", idFrom);
            cmd.Parameters.AddWithValue("@idTo", idTo);
            SqlDataReader reader;

            conn.Open();
            reader = cmd.ExecuteReader();
            reader.Read();

            if (!reader.HasRows)
            {
                return 0;
            }
            else
            {
                string temp = (string)reader["friendreq_status"];
                if (temp == "Sent")
                    return 1;
                else
                    return 2;
            }
        }
        
        public static void UpdateProfilePic(int userId, string serverPath)
        {
            string updateSql = "UPDATE [user] SET "
                                + "user_pic = @userPic "
                                + "WHERE user_id = @userId ";
            SqlConnection conn = new SqlConnection(Common.connString);
            SqlCommand cmd = new SqlCommand(updateSql, conn);
            cmd.Parameters.AddWithValue("@userPic", serverPath);
            cmd.Parameters.AddWithValue("@userId", userId);

            try
            {
                using (conn)
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception profileEditEx)
            {
                Common.WriteToEventLog(profileEditEx, "UpdateProfilePictureUrl");
                throw profileEditEx;
            }
        }

        public static void WriteToEventLog(Exception e, string action)
        {
            EventLog log = new EventLog();
            log.Source = "QTMusic";
            log.Log = "Application";

            string message = "Xuất hiện ngoại lệ.\n\n";
            message += "Thao tác: " + action + "\n\n";
            message += "Ngoại lệ: " + e.ToString();

            //log.WriteEntry(message);
        }

        //public static UserControl LoadControl(string UserControlPath, params object[] constructorParameters)
        //{
        //    List constParamTypes = new List();
        //    foreach (object constParam in constructorParameters)
        //    {
        //        constParamTypes.Add(constParam.GetType());
        //    }

        //    UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;

        //    // Find the relevant constructor
        //    ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());

        //    //And then call the relevant constructor
        //    if (constructor == null)
        //    {
        //        throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
        //    }
        //    else
        //    {
        //        constructor.Invoke(ctl, constructorParameters);
        //    }

        //    // Finally return the fully initialized UC
        //    return ctl;
        //}
    }
}